package rlb;

import robocode.HitWallEvent;
import robocode.Robot;
import robocode.ScannedRobotEvent;
import java.awt.Color;
import robocode.WinEvent;
import robocode.HitRobotEvent;
import static robocode.util.Utils.normalRelativeAngleDegrees;
import robocode.HitByBulletEvent;
import robocode.BulletMissedEvent;

/**
 * 
 * FlankBot: Scans for Target and Flanks and Fires.
 * 
 * @author Remy Baumgarten
 * 
 */
public class FlankBot extends Robot {

  private double angle = 10;
  private int missed = 0;

  /**
   * Change Colors and Spin Radar.
   */
  public void run() {
    setBodyColor(Color.black);
    setGunColor(Color.yellow);
    setRadarColor(Color.red);
    setScanColor(Color.white);
    setBulletColor(Color.white);

    while (true) {
      turnRadarRight(180);
      ahead(50);
    }
  }

  /**
   * ScannedRobotEvent - Flank upon Target.
   * 
   * @param e enemy
   */
  public void onScannedRobot(ScannedRobotEvent e) {
    // Point Gun at Target
    angle = normalRelativeAngleDegrees(e.getBearing() + (getHeading() - getGunHeading()));
    System.out.println(angle);
    // Is it a Walls Bot?
    if (e.getName().indexOf("wall") > 0 || e.getName().indexOf("Wall") > 0) {
      turnGunRight(angle + 30);
    }
    else {
      turnGunRight(angle);
    }
    // Fire depending on Distance of Target
    if (e.getDistance() > 30) {
      // If continually missing, don't waste energy
      if (missed < 20) {
        fire(1);
      }
    }
    else if (e.getDistance() >= 0 && e.getDistance() <= 30) {
      fire(3);
    }

    // Flank Action
    turnRight(e.getBearing() - 90);
    ahead(100);
  }

  /**
   * ScannedRobotEvent - Flank upon Target.
   * 
   * @param e enemy
   */
  public void onHitWall(HitWallEvent e) {
    turnRight(90);
    ahead(200);
  }

  /**
   * ScannedRobotEvent - Flank upon Target.
   * 
   * @param e enemy
   */
  public void onHitRobot(HitRobotEvent e) {
    // Fire full Power at Target
    angle = normalRelativeAngleDegrees(e.getBearing() + (getHeading() - getGunHeading()));
    turnGunRight(angle);
    fire(3);
    // Move Away
    turnRight(e.getBearing() - 120);
    ahead(200);
  }

  /**
   * Move after getting hit.
   * 
   * @param e enemy
   */
  public void onHitByBullet(HitByBulletEvent e) {
    turnLeft(90);
  }

  /**
   * If Bullet misses over 10 times reserve shots.
   * 
   * @param event BulletMissedEvent
   */
  public void onBulletMissed(BulletMissedEvent event) {
    missed++;
  }
  
  /**
   * For Future Unit Test to Check if we Shoot when Missed is Over Threshold.
   * @return missed bullets
   */
  public int getMissed() {
    return missed;
  }

  /**
   * ScannedRobotEvent - Flank upon Target.
   * 
   * @param e enemy
   */
  public void onWin(WinEvent e) {
    turnGunRight(1080);
    turnGunLeft(1080);
    for (int i = 0; i < 3; i++) {
      fire(1);
    }
  }

}
